package service

import (
	"first/migrate"
	"first/model"
	"fmt"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func GetUsers(c *gin.Context) {
	var users []model.User
	migrate.DB.Find(&users)
	c.JSON(200, users)
}

func CreateUser(c *gin.Context) {
	var user model.User
	if err := c.ShouldBindJSON(&user); err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}

	migrate.DB.Create(&user)
	c.JSON(200, user)
}

// 根据用户名查询用户
func GetUserByUsername(username string) (*model.User, error) {
	var user model.User
	result := migrate.DB.Where("username = ?", username).First(&user)
	if result.Error != nil {
		if result.Error == gorm.ErrRecordNotFound {
			fmt.Println("User not found")
		} else {
			fmt.Println(result.Error)
		}
	}
	// 输出查询结果
	fmt.Printf("User: %+v\n", user)
	return &user, nil
}
